package com.xxgg.system.aspectj;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.xxgg.common.annotation.OpenLog;
import com.xxgg.system.model.po.Logs;
import com.xxgg.system.service.LogsService;
import com.xxgg.common.utils.JsonUtils;
import com.xxgg.common.utils.servlet.AddressUtils;
import com.xxgg.common.utils.servlet.ServletUtils;
import com.xxgg.common.utils.spring.SpringUtils;
import com.xxgg.common.utils.string.StringUtils;
import com.xxgg.system.service.UserService;
import io.swagger.models.HttpMethod;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;

/**
 * 操作日志记录处理
 *
 * @author 先谢郭嘉
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Resource
    UserService userService;


    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(openLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, OpenLog openLog, Object jsonResult) {
        handleLog(joinPoint, openLog, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(openLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, OpenLog openLog, Exception e) {
        handleLog(joinPoint, openLog, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, OpenLog openLog, final Exception e, Object jsonResult) {
        if(!StpUtil.isLogin()) return;

        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

            Logs logs = new Logs();
            // 请求方式
            logs.setRequestMethod(ServletUtils.getRequest().getMethod());
            // 请求方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            // 方法名称（英文）
            logs.setMethodNameEn(className + "." + methodName + "()");
            // 请求URL
            logs.setUrl(ServletUtils.getRequest().getRequestURL().toString());
            // 主机地址
            logs.setIp(AddressUtils.getIp(request));
            // 操作地点
            logs.setLocation(AddressUtils.getRealAddressByIP(logs.getIp()));
            // 操作时间
            logs.setLogTime(new Timestamp(System.currentTimeMillis()));
            // 操作用户
            logs.setUserName(userService.getById(StpUtil.getLoginId().toString()).getUserName());

            // 处理设置注解上的参数
            getMethodDescription(joinPoint, openLog, logs, jsonResult);

            // 保存数据库
            SpringUtils.getBean(LogsService.class).getBaseMapper().insert(logs);
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("日志记录异常:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     * @param joinPoint
     * @param openLog
     * @param logs
     * @param jsonResult
     * @throws Exception
     */
    public void getMethodDescription(JoinPoint joinPoint, OpenLog openLog, Logs logs, Object jsonResult) throws Exception {
        // 操作模块
        logs.setModule(openLog.module());
        // 业务操作类型
        logs.setBusinessType(openLog.businessType().getTypeCode());
        // 方法名称（中文）
        logs.setMethodNameZh(openLog.name());
        // 是否需要保存request，参数和值
        if (openLog.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, logs);
        }
        // 是否需要保存response，参数和值
        if (openLog.isSaveResponseData() && ObjectUtil.isNotNull(jsonResult)) {
            logs.setResult(StringUtils.substring(JsonUtils.toJsonString(jsonResult), 0, 2000));
        }
        // 接口请求状态
        logs.setRequestCode(new JSONObject(jsonResult).getStr("code"));
    }

    /**
     * 获取请求的参数，放到logs中
     *
     * @param logs 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, Logs logs) throws Exception {
        String requestMethod = logs.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            logs.setParam(StringUtils.substring(params, 0, 2000));
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            logs.setParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (ObjectUtil.isNotNull(o) && !isFilterObject(o)) {
                    try {
                        params.append(JsonUtils.toJsonString(o)).append(" ");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
            || o instanceof BindingResult;
    }
}
